<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class ResetAction extends BaseAccountAction {

	//忘记密码表单
	public function index() {
		$this->display();
	}

	public function save() {
		$email = trim($_POST["email"]);
		$password = $_POST["password"];
		$repassword = $_POST["repassword"];
		empty($password) && $this->error("密码不能为空");
		strlen($password) < 5 && $this->error('新密码长度必须大于 5 个字符!');
		$password != $repassword && $this->error('两次新密码不相同!');
		if (!empty($email) && !Model::regex($email, "email"))
			$this->error("邮箱格式错误");
		$user = D("User")->getByEmail($email);
		if (empty($user))
			$this->error("账号不存在");

		//相关信息存入数据库
		$Reset = D('ResetLog');
		$guid = $Reset->query("select uuid() as guid");
		$data['password'] = md5($password);
		$data['email'] = $email;
		$data['guid'] = $guid[0]["guid"];
		$data['user_id'] = $user["user_id"];
		$data['create_time'] = time();
		//发送邮件
		$vo = send_mail($email, "密码修改 来自" . C("SITE_NAME"), "reset", array(
			"site_url" => C("SITE_URL"),
			"email" => $email,
			"guid" => $guid[0]["guid"],
			"uid" => $user["user_id"],
			));
		if ($vo) {
			//发送成功，写入数据
			$Reset->data($data)->add();
			$this->success('请登录您的注册邮箱，继续完成密码修改操作!',C("SITE_URL"));
		} else {
			$this->error('邮件发送失败，请重试或联系管理员!');
		}
	}

	//验证&修改成功
	public function verify() {
		//获取当前时间
		$currentTime = time();

		$data['guid'] = $_GET['token'];
		$data['user_id'] = $_GET['key'];
		empty($data['guid']) && $this->error('修改失败，请重试!');
		empty($data['user_id']) && $this->error('修改失败，请重试!');

		$Reset = D('ResetLog')->where($data);
		$_reset = $Reset->find();
		//获取最后期限
		$endTime = $_reset['create_time'] + 48 * 3600;
		//判断是否过期
		$currentTime > $endTime && $this->error('链接已过期!');
		if ($_reset) {
			//更新数据
			D('User')->where('user_id =' . $data['user_id'])->setField('password', $_reset["password"]);
			$Reset->delete($_reset["reset_id"]);
			$this->success('密码修改成功!', __GROUP__ . "/");
		} else {
			$this->error('链接已过期!', __GROUP__ . "/Reset");
		}
	}

}

?>
